from nbhttpconnection import NBHTTPConnection
import time, re, urllib, socket, HTMLParser

def MovieLookup(input, debug=False):
    #Amazon Prime uses a lot of titles like: 13 Assassins (English Subtitled)
    #This area removes the ' (English Subtitled)' portion of the imput
    #if it exists
    cleanedInput = re.search(r'(.+?)\s\(.+$|(.+)', input, re.IGNORECASE)
    if cleanedInput.group(1) != None:
        input = cleanedInput.group(1)
    req = urllib.urlencode({'query' : input, 'api_key' : 'c82628330a739e5fd5b27ff39e7d5f16'})
    if debug:
        print "[Follwit Episode Lookup] Running lookup for: " + req
    host = 'api.themoviedb.org'
    req = "/3/search/movie?" + req
    try:
        conn = NBHTTPConnection(host)
    except socket.timeout:
        print '[Follwit API] socket timeout excecption'
        conn = None
    if conn == None:
        if debug:
            print 'Unable to connect to tmdb'
        return    
    try:
        conn.request('GET', req, None, {'accept' : 'application/json'})
    except socket.error:
        if debug:
            print 'Unable to connect to tmdb'
        conn.close()
        return
    
    conn.go()
    
    timeout = 0
    while timeout < 60:
        if conn.hasResult():
            break
        timeout = timeout + 1
        time.sleep(1)
    
    if timeout == 60:
        if debug:
            print '[Follwit API] Request has timed out.'
        conn.close()
        return
    
    response = conn.getResult()
    raw = response.read()
    
    if debug:
        print "[Follwit Episode Lookup] Raw responce " + raw
    
    conn.close()
    match = re.findall(r'"id"\:(\d+),"original_title"\:"(.+?)".+?"title"\:"(.+?)"', raw, re.IGNORECASE)
    
    result = None
    try:
        parser = HTMLParser.HTMLParser()
        for res in match:
            if parser.unescape(res[1]).lower() == input.lower():
                result = res[0]
                break
            if parser.unescape(res[2]).lower() == input.lower():
                result = res[0]
                break
    except:
        result = None
    
    return result
        
    